<?php
declare (strict_types = 1);
namespace app\common\controller;

use app\BaseController;
use app\common\error\Base as BaseResponse;
use app\common\logic\BaseLogic;
use think\App;

/**
 * 系统通用控制器基类
 */
class ControllerBase extends BaseController
{
    /**
     * 应用实例
     * @var \think\App
     */
    protected $params = [];


    /**
     * 基类初始化
     */
    public function __construct(App $app = null){
        //继承父类
        parent::__construct($app);

        // 初始化请求信息
        $this->initRequestInfo();

        // 初始化请求变量
        $this->initParams();

    }
    /**
     * 初始化请求信息
     */
    final private function initRequestInfo(){
        defined('IS_POST') or define('IS_POST', $this->request->isPost());
        defined('IS_GET') or define('IS_GET', $this->request->isGet());
        defined('IS_PUT') or define('IS_PUT', $this->request->isPut());
        defined('IS_DELETE') or define('IS_DELETE', $this->request->isDelete());
        defined('IS_OPTIONS') or define('IS_OPTIONS', $this->request->isOptions());
        defined('IS_AJAX') or define('IS_AJAX', $this->request->isAjax());
        defined('IS_PJAX') or define('IS_PJAX', $this->request->isPjax());
        defined('IS_MOBILE') or define('IS_MOBILE', $this->request->isMobile());
        defined('IS_HEAD') or define('IS_HEAD', $this->request->isHead());
        defined('METHOD') or define('METHOD', strtolower($this->request->method()));
    }

    /**
     * 初始化请求参数
     */
    final protected function initParams(){

        $this->params = $this->request->param(false);

    }

    /**
     * 公用返回数据
     */
    public static function returnData($code_data = [], $return_data = []){

        if (is_array($code_data)) {

            $code_data[RESULT_SUCCESS] = $code_data[RESULT_SUCCESS] ?? true;

            $code_data[RESULT_CODE] = $code_data[RESULT_CODE] ?? 200;

            $code_data[RESULT_MESSAGE] = $code_data[RESULT_MESSAGE] ?? 'success';

            !empty($return_data) && $code_data[RESULT_DATA] = $return_data;

            $result = $code_data;

        } else {

            $result = BaseResponse::$success;

            $result[RESULT_SUCCESS] = true;

            $result['data'] = $code_data;

        }

        if($result[RESULT_CODE] <= 600 ){

            BaseLogic::responseData($result,true);

        }

        return json($result);

    }


}
